from django.shortcuts import render

# Create your views here.


from django import http
from django.views import View
from apps.users.models import User
import json, re
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from celery_tasks.email.tasks import send_verify_email
from apps.users.utils import generate_verify_email_url, check_verify_email_token
from apps.users.models import Address
from apps.goods.models import SKU
from apps.users.serializers import UserSerializer,AddressSerializer,RegisterModelSerializer


import logging

logger = logging.getLogger('django')


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        '''判断用户名是否重复'''
        # 1.查询username在数据库中的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '访问数据库失败'})

        # 2.返回结果(json) ---> code & errmsg & count
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'count': count})


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        '''判断手机号是否重复注册'''
        # 1.查询mobile在mysql中的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '查询数据库出错'})

        # 2.返回结果(json)
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'count': count})


class RegisterView(View):
    """用户注册视图"""

    def post(self, request):
        # # 前后端分离，ajax只识别json数据，所以这里请求体是json数据
        # json_bytes = request.body
        # # 把json原始数据转成字符串，再转成字典，这样好取值
        # json_str = json_bytes.decode()
        # json_dict = json.loads(json_str)
        # # json_dict = json.loads(request.body.decode())  一行就能写完 固定写法
        # # 1.提取参数
        # username = json_dict.get('username')
        # password = json_dict.get('password')
        # password2 = json_dict.get('password2')
        # mobile = json_dict.get('mobile')
        # sms_code = json_dict.get('sms_code')
        # allow = json_dict.get('allow')
        #
        # # 2.判断是否缺少必传参数以及参数格式是否正确
        # # all([]) python中提供的 判断某些数据中是否有为空的数据,任何一个元素为空返回false
        # if not all([username, password, password2, mobile, sms_code, allow]):
        #     return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        #
        # # 3.username检验
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误'})
        #
        # # 4.password检验
        # if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})
        #
        # # 5.password2 和 password
        # if password != password2:
        #     return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})
        # # 6.mobile检验
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})
        # # 7.allow检验
        # if allow != True:
        #     return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误'})
        #
        # # 8.sms_code检验 (链接redis数据库)
        # redis_conn = get_redis_connection('verify_code')
        #
        # # 9.从redis中取值
        # sms_code_server = redis_conn.get('sms_%s' % mobile)
        #
        # # 10.判断该值是否存在
        # if not sms_code_server:
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证码过期'})
        #
        # # 11.把redis中取得值和前端发的值对比
        # if sms_code != sms_code_server.decode():
        #     return http.JsonResponse({'code': 400, 'errmsg': '验证码有误'})
        #
        # # 12.保存到数据库 (username password mobile)
        # try:
        #     user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # except Exception as e:
        #     return http.JsonResponse({'code': 400, 'errmsg': '保存到数据库出错'})


        # 用序列化器实现注册
        json_dict = json.loads(request.body.decode())
        serializer = RegisterModelSerializer(data=json_dict)
        if serializer.is_valid():
            user = serializer.save()
        else:
            return http.JsonResponse({'code': 400, 'errmsg': '保存到数据库出错'})

        # 登录状态保持
        login(request, user)

        # 13.拼接json返回
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 后端把数据保存到 cookie 中, 前端访问 cookie 获取信息后加载到页面,让页面显示用户名信息
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response


class LoginView(View):
    """用户登录"""

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        # 实现多账号登录 不只是用户名可以登录 也可以是手机号码
        account = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 2.校验(整体 + 单个)
        if not all([account, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 2.2.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})

        # 实现多账号登录
        # 判断用户是否是手机号码还是用户名
        # Django默认是用用户名进行登录的校验的，底层源码中 USERNAME_FIELD 默认指向的是用户名字段
        # 想要用手机号登录 判断是手机号时，将 USERNAME_FIELD 指向手机号字段
        if re.match(r'^1[3-9]\d{9}$', account):
            # 如果是手机号，USERNAME_FIELD 指定为‘mobile’字段
            User.USERNAME_FIELD = 'mobile'
        else:
            # 如果是用户名，USERNAME_FIELD 指定为‘username’字段
            User.USERNAME_FIELD = 'username'

        # 3.验证是否能够登录
        user = authenticate(request=request, username=account, password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或者密码错误'})

        # 4.状态保持
        login(request, user)

        # 5.判断是否记住用户
        if remembered != True:
            # 7.如果没有记住: 关闭立刻失效
            request.session.set_expiry(0)
        else:
            # 6.如果记住:  设置为两周有效
            request.session.set_expiry(None)

        # 8.返回json
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 后端把数据保存到 cookie 中, 前端访问 cookie 获取信息后加载到页面,让页面显示用户名信息
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 用户登录，合并购物车
        from apps.carts.utils import merge_cart_cookie_to_redis
        response = merge_cart_cookie_to_redis(request,user,response)

        return response


class LogoutView(View):
    """退出登录"""

    # 请求方式 delete
    def delete(self, request):
        # 清理登录状态
        logout(request)
        # 清理用户名cookie
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')
        return response


class UserInfoView(LoginRequiredJSONMixin, View):
    """用户中心"""

    # LoginRequiredJSONMixin 是继承 LoginRequiredMixin 类的 LoginRequiredMixin他是Django 里封装好的 用来判断是否是登录状态的  如果登录 就进入
    # 想要的页面，如果没有登录就返回到登录页面  我们的需求是如果没有登录 返回json数据 所以要重写LoginRequiredJSONMixin 里handle_no_permission方法
    # 因为 handle_no_permission 方法是处理没有登录后返回页面的逻辑 我们重写直接返回 json 数据 详情找meiduo_mall.utils.views里的代码

    # session机制的认证登录状态中，当我们使用login去保持状态登录后，Django中的AuthenticationMiddleware这个中间件的process_request函数中，
    # 实现了从cookie中获取携带的session_key，再去session共享服务器Redis中获取user_id，通过user_id获取user对象，赋值给request.user
    # 所以当我们实现了判断用户是否登录，用户状态保持，我们就能直接使用 request.user ，直接可以得到当前用户对象

    def get(self, request):

        # 之前的代码
        # data_dict = {
        #     'code': 0,
        #     'errmsg': 'ok',
        #     'info_data': {
        #         'username': request.user.username,
        #         'mobile': request.user.mobile,
        #         'email': request.user.email,
        #         'email_active': request.user.email_active,
        #     }
        # }

        # 使用序列化器生成字典
        data_dict = {
            'code': 0,
            'errmsg': 'ok',
            'info_data': UserSerializer(instance=request.user).data
        }
        return http.JsonResponse(data_dict)


class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱"""

    def put(self, request):
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少email参数'})
        # 判断邮箱格式是否正确
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '添加email失败'})

        # 调用发送邮件的函数:
        verify_url = generate_verify_email_url(request.user)
        send_verify_email.delay(email, verify_url)

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class VerifyEmailView(View):
    """验证邮箱"""

    def put(self, request):
        """实现邮箱验证逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数：判断 token 是否为空和过期，提取 user
        if not token:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少token'})

        # 调用上面封装好的方法, 将 token 传入
        user = check_verify_email_token(token)
        if not user:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '无效的token'})

        # 修改 email_active 的值为 True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '激活邮件失败'})

        # 返回邮箱验证结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})


class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""

        # 获取地址个数:
        try:
            # count = Address.objects.filter(user=request.user,is_deleted=False).count()
            count = request.user.addresses.filter(is_deleted=False).count()  # 一查多的自关联查询写法
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '获取地址数据出错'})
            # 判断是否超过地址上限：最多20个
        if count >= 20:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address': address_dict})


class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        # addresses = Address.objects.filter(user=request.user,is_deleted=False)
        addresses = request.user.addresses.filter(is_deleted=False)  # 一查多写法
        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            # 以前的代码
            # address_dict = {
            #     "id": address.id,
            #     "title": address.title,
            #     "receiver": address.receiver,
            #     "province": address.province.name,
            #     "city": address.city.name,
            #     "district": address.district.name,
            #     "place": address.place,
            #     "mobile": address.mobile,
            #     "tel": address.tel,
            #     "email": address.email
            # }

            # 用序列化器实现对象转字典
            address_dict = AddressSerializer(instance=address).data

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'addresses': address_dict_list,
                                  'default_address_id': default_id})


class UpdateDestroyAddressView(View):
    """修改删除收货地址"""

    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        try:
            # update必须与filter一起使用
            Address.objects.filter(id=address_id).update(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改地址失败'})

        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'address': address_dict})

    def delete(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '删除收货地址错误'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class DefaultAddressView(View):
    """修改默认收货地址"""

    def put(self, request, address_id):
        try:
            request.user.default_address_id = address_id
            request.user.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改默认地址失败'})

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})


class UpdateTitleAddressView(View):
    """修改收货地址标题"""

    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改默认地址失败'})

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})


class ChangePasswordView(LoginRequiredJSONMixin, View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not request.user.check_password(old_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '原始密码输入不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一致'})
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改密码失败'})

        # 修改了密码了要清理之前的状态保持信息
        logout(request)
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')

        return response


class UserBrowseHistory(View):
    """用户浏览记录"""

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数sku_id不存在'})

        # 链接redis数据库，去重，添加，截取数据
        redis_conn = get_redis_connection('history')

        # 开启管道
        pl = redis_conn.pipeline()
        pl.lrem('history_%s' % request.user.id, 0, sku_id)
        pl.lpush('history_%s' % request.user.id, sku_id)
        pl.ltrim('history_%s' % request.user.id, 0, 4)
        pl.execute()

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})

    def get(self, request):
        redis_conn = get_redis_connection('history')
        skus_id_list = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        skus = []
        for sku_id in skus_id_list:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                "id": sku.id,
                "name": sku.name,
                "default_image_url": sku.default_image.url,
                "price": sku.price
            })

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': skus})

